// Renderer process
const { contextBridge, ipcRenderer } = require("electron");
const { getFileDetails } = require("../file-detail.js");
contextBridge.exposeInMainWorld("electronAPI", {
  getFileDetails,
  postMessage: (
    channel = "port-upload",
    newItem,
    funcMessage = () => {},
    funcClose = () => {}
  ) => {
    const { port1, port2 } = new MessageChannel();
    console.log("port2", port2);
    port2.onmessage = (messageEvent) => {
      if (!(messageEvent && messageEvent.data)) {
        console.log("onmessage1 messageEvent", messageEvent);
        return;
      }
      console.log("onmessage2", messageEvent.data);

      funcMessage(messageEvent.data);
    };
    port2.onmessageerror = (messageEvent) => {
      funcClose("onmessageerror", messageEvent);
    };
    port2.onclose = (messageEvent) => {
      funcClose("onclose", messageEvent);
    };
    port2.start(); // 开始接收消息
    ipcRenderer.postMessage(channel, newItem, [port1]);
    return {
      close: () => port2.close(),
      postMessage: (...reset) => port2.postMessage(...reset),
    };
  },
  invoke: (channel, ...reset) => {
    return ipcRenderer.invoke(channel, ...reset);
  },
});
